import { upload } from "@/api";
import { useMitt } from "@/hooks/useMitt";
import { useChat } from "@/store/modules/chat";
import { IFile, IMessage, MessageStatus } from "@/types/chat";
import { IFileListItem, IFileListRes } from "@/types/file";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import { computed, ref } from "vue";

// 格式化文件大小
export function FormatFileSize(sizeInBytes: number | undefined): string {
  if (!sizeInBytes) return "0";
  if (sizeInBytes < 1024) {
    return `${sizeInBytes} B`;
  } else if (sizeInBytes < 1024 * 1024) {
    const sizeInKB = (sizeInBytes / 1024).toFixed(2);
    return `${sizeInKB} KB`;
  } else if (sizeInBytes < 1024 * 1024 * 1024) {
    const sizeInMB = (sizeInBytes / (1024 * 1024)).toFixed(2);
    return `${sizeInMB} MB`;
  } else {
    const sizeInGB = (sizeInBytes / (1024 * 1024 * 1024)).toFixed(2);
    return `${sizeInGB} GB`;
  }
}

//base64转文件
export function Base64ToFile(base64: string, filename: string = "image"): File {
  const [meta, content] = base64.split(",");
  const mime = meta.match(/:(.*?);/)?.[1] || "image/png";
  const ext = mime.split("/")[1];
  const byteStr = atob(content);
  const u8arr = new Uint8Array(byteStr.length);
  for (let i = 0; i < byteStr.length; i++) u8arr[i] = byteStr.charCodeAt(i);
  return new File([u8arr], `${filename}.${ext}`, { type: mime });
}

//blob转文件
export function BlobToFile(data: any, name: string = "avatar", ext: string = "png") {
  let fileName = name + "." + ext;
  return new File([data], fileName, {
    type: "text/plain",
    lastModified: Date.now(),
  });
}

// 检查文件大小
export function CheckFileSize(file: File, maxSizeMB = 5): boolean {
  const maxSize = maxSizeMB * 1024 * 1024;
  if (file.size > maxSize) {
    ElMessage.error("超出上传文件大小");
    return true;
  }
  return false;
}

// 预览文件
export function ViewImageFile(file: File, callback: Function = () => {}): Promise<IFile> {
  return new Promise<IFile>(async (resolve) => {
    let obj: IFile = {
      file: file,
      viewUrl: "",
      type: 2,
    };

    if (file.type.startsWith("image/")) {
      obj.type = 1;
      const reader = new FileReader();
      reader.onload = () => {
        obj.viewUrl = reader.result as string;
        callback();
        resolve(obj);
      };

      reader.onerror = () => {
        console.error("Error reading the file.");
        resolve(obj);
      };

      reader.readAsDataURL(file);
    } else {
      obj.type = 2;
      obj.viewUrl = GetFileTypeIcon.value(file.name);
      resolve(obj);
    }
  });
}

// 获取文件类型
export const GetFileTypeIcon = computed(() => {
  return (filename: string): string => {
    if (!filename) return "";
    const fileType = filename.split(".").pop()?.toLowerCase() || "unknown";
    return new URL(`../assets/fileIcon/${fileType}.svg`, import.meta.url).href;
  };
});

// 处理文件上传进度显示
export async function HandelFileUploadProgress(message: IMessage, file: File, callBack?: () => void) {
  const { MessageList } = storeToRefs(useChat());
  const abortController = new AbortController();

  if (!file) {
    ElMessage.error("上传文件不能为空");
    return;
  }
  const msg = ref(
    Object.assign(message, {
      upload: true,
      progress: 0,
      status: MessageStatus.wait,
    }),
  );
  MessageList.value.push(msg.value);
  useMitt.emit("scrollBottom", true);
  try {
    const formData = new FormData();
    formData.append("file", file);
    const res = await upload(formData, {
      signal: abortController.signal,
      onUploadProgress(event: any) {
        if (event.lengthComputable) {
          const percent = Math.min(100, Math.round((event.loaded * 100) / event.total));
          if (percent !== msg.value.progress) {
            msg.value.progress = percent;
          }
        }
      },
    });
    if (res?.status !== 200) throw new Error("上传失败，请检查格式");
    msg.value = Object.assign(message, {
      upload: false,
      progress: 100,
      status: MessageStatus.success,
      fileUrl: res.data,
    });
    window.electronApi.sendMessage({ ...message, fileUrl: res.data });
  } catch (error: any) {
    if (error.name !== "AbortError") {
      msg.value = Object.assign(message, {
        upload: false,
        progress: -1,
        status: MessageStatus.error,
      });
      ElMessage.error(error.message || "上传失败");
    }
  } finally {
    callBack?.();
  }

  return () => {
    abortController.abort();
    msg.value = Object.assign(message, {
      upload: false,
      progress: 0,
      status: MessageStatus.cancel,
    });
  };
}

// 处理文件列表
export function HandelFileList(list: IFileListRes[]): IFileListItem[] {
  return list.map((item) => {
    if (item.localPath === null) {
      return { ...item, progress: 0, downloaded: false };
    }
    return { ...item, progress: 100, downloaded: true };
  });
}
